# coding:utf-8

from datetime import datetime, date

from flask import request
from flask_admin._compat import urlparse, urljoin

from . import db
from .main.models import Material


def prettify_name(name):
    """
        Prettify pythonic variable name.

        For example, 'hello_world' will be converted to 'Hello World'

        :param name:
            Name to prettify
    """
    return name.replace('_', ' ').title()


def get_mdict_item_or_list(mdict, key):
    """
        Return the value for the given key of the multidict.

        A werkzeug.datastructures.multidict can have a single
        value or a list of items. If there is only one item,
        return only this item, else the whole list as a tuple

        :param mdict: Multidict to search for the key
        :type mdict: werkzeug.datastructures.multidict
        :param key: key to look for
        :return: the value for the key or None if the Key has not be found
    """
    if hasattr(mdict, 'getlist'):
        v = mdict.getlist(key)
        if len(v) == 1:
            value = v[0]

            # Special case for empty strings, treat them as "no-value"
            if value == '':
                value = None

            return value
        elif len(v) == 0:
            return None
        else:
            return tuple(v)
    return None


def is_safe_url(target):
    ref_url = urlparse(request.host_url)
    test_url = urlparse(urljoin(request.host_url, target))
    return (test_url.scheme in ('http', 'https') and
            ref_url.netloc == test_url.netloc)


def get_redirect_target(param_name='url'):
    target = request.values.get(param_name)

    if target and is_safe_url(target):
        return target


def batch_insert_data(file_object=None):
    for line in file_object:
        material = Material()
        if str(line).startswith('#'):
            pass
        else:
            fields_list = str(line).split('#')
            if len(fields_list) == 7:
                (material.name, material.keywords, material.storage_time,
                 material.location, material.description, material.picture, material.expiration) \
                    = [t.strip().decode('utf-8') for t in fields_list]
                material.storage_time = datetime.strptime(material.storage_time, '%Y-%m-%d %H:%M:%S')
                if material.expiration:
                    date_data = [int(t) for t in material.expiration.split('-')]
                    material.expiration = date(date_data[0], date_data[1], date_data[2])
                db.session.add(material)
    db.session.commit()

